package com.vigor.bear.web.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.vigor.bear.mybatis.Pagination;
import com.vigor.bear.web.bean.Info;
import com.vigor.bear.web.service.InfoService;
import com.vigor.bear.web.utils.FileUtil;

@Controller
@RequestMapping("/info")
public class InfoController extends BaseController {
	
	private static final int BUFFER_SIZE = 100 * 1024;
	private static final String RELATIVE_PATH = "/plupload/files/";
	private static final Logger logger = Logger.getLogger(InfoController.class);

	@Autowired
	private InfoService isv;

	@InitBinder("info")
	public void initUserBinder(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("info.");
	}

	@RequestMapping(method = RequestMethod.GET)
	public String view(Model model, Info info) {
		this.getList(isv, model, info);
		return "course/info/list";
	}

	@RequestMapping(value = "/list/{pageNow}/{pageSize}", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> list(@PathVariable("pageNow") String pageNow,
			@PathVariable("pageSize") String pageSize, Info info) {
		return getList(isv, pageNow, pageSize, info);
	}

	@RequestMapping(value = "/search", method = RequestMethod.POST)
	public String search(Info info, Model model) {
		this.getList(isv, model, info);
		return "course/info/list";
	}

	/**
	 * 使用plupload上传文件
	 * 
	 * @param file
	 *            文件对象
	 * @param name
	 *            文件名称
	 * @param chunk
	 *            数据块序号
	 * @param chunks
	 *            数据块总数
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/plupload", method = RequestMethod.POST)
	public String plupload(@RequestParam MultipartFile file,
			HttpServletRequest request, HttpSession session) {
		Info info = new Info();

		try {
			String name = request.getParameter("name");
			Integer chunk = 0, chunks = 0;
			if (null != request.getParameter("chunk")
					&& !request.getParameter("chunk").equals("")) {
				chunk = Integer.valueOf(request.getParameter("chunk"));
			}
			if (null != request.getParameter("chunks")
					&& !request.getParameter("chunks").equals("")) {
				chunks = Integer.valueOf(request.getParameter("chunks"));
			}
			logger.info("chunk:[" + chunk + "] chunks:[" + chunks + "]");
			// 检查文件目录，不存在则创建
			String realPath = session.getServletContext().getRealPath("");
			File folder = new File(realPath + RELATIVE_PATH);
			if (!folder.exists()) {
				folder.mkdirs();
			}

			// 目标文件
			File destFile = new File(folder, name);
			// 文件已存在删除旧文件（上传了同名的文件）
			if (chunk == 0 && destFile.exists()) {
				destFile.delete();
				destFile = new File(folder, name);
			}
			// 合成文件
			FileUtil.appendFile(file.getInputStream(), destFile, BUFFER_SIZE);
			if (chunk == chunks - 1) {
				logger.info("上传完成");
			} else {
				logger.info("还剩[" + (chunks - 1 - chunk) + "]个块文件");
			}

			// 保存资料
			info.setName(name);
			info.setFiletype(name.substring(name.lastIndexOf(".") + 1));
			info.setSize(FileUtil.convertFileSize(file.getSize()));
			info.setPath(folder.getCanonicalPath());
			info.setUpload_user((String) SecurityUtils.getSubject()
					.getPrincipal());
			this.createInfo(info);

		} catch (IOException e) {
			logger.error(e.getMessage());
		}

		return "";
	}

	private void createInfo(Info info) {
		int ret = isv.create(info);
		if (ret > 0) {
			logger.info("资料保存成功");
		} else {
			logger.info("资料保存失败");
		}
	}

	private static List<String> getFileType() {
		List<String> typeList = new ArrayList<String>();
		typeList.add(".docx");
		typeList.add(".xlsx");
		typeList.add(".pptx");
		typeList.add(".zip");
		return typeList;
	}

	private void getList(InfoService isv, Model model, Info info) {
		Pagination pagination = getPagination();

		List<Info> list = isv.search(pagination, info == null ? new Info()
				: info);

		if (list != null && list.size() > 0) {
			model.addAttribute("records", list);
		}

		model.addAttribute("totalCounts", pagination.getTotal());
		model.addAttribute("pageSize", pagination.getSize());
		model.addAttribute("totalPages", pagination.getPages());
		model.addAttribute("info", info == null ? new Info() : info);

		// 填充select下拉条件,用来测试
		model.addAttribute("fileType", getFileType());
	}

	private Map<String, Object> getList(InfoService isv, String pageNow,
			String pageSize, Info info) {
		Pagination pagination = getPagination(pageNow, pageSize);
		List<Info> list = isv.search(pagination, info);

		Map<String, Object> map = new HashMap<String, Object>();
		if (list != null && list.size() > 0) {
			map.put("records", list);
		}
		map.put("pageSize", pagination.getSize());
		map.put("totalPages", pagination.getPages());
		map.put("totalCounts", pagination.getTotal());

		return map;
	}

}
